<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;


/**
 * App\Models\PostCatlog
 *
 * @property int $catid
 * @property int $fid 父级分类
 * @property string $name 分类名称
 * @property string $identifier
 * @property string $icon 图片
 * @property int $level 级别
 * @property int $enable 是否可选
 * @property int $available 是否可用
 * @property int $displayorder 显示顺序
 * @property string $keywords 关键字
 * @property string $description 描述
 * @property string $template_index 首页模板
 * @property string $template_list 列表页模板
 * @property string $template_detail 详细页模板
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\PostCatlog[] $childs
 * @property-read \App\Models\PostCatlog $parent
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\PostItem[] $posts
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog available()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog enable()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereAvailable($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereCatid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereDescription($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereDisplayorder($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereEnable($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereFid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereIcon($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereIdentifier($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereKeywords($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereLevel($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereTemplateDetail($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereTemplateIndex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\PostCatlog whereTemplateList($value)
 * @mixin \Eloquent
 */
class PostCatlog extends Model
{
    protected $table = 'post_catlog';
    protected $primaryKey = 'catid';
    protected $guarded = ['catid'];

    public $timestamps = false;


    /**
     * @param int $default
     * @param array $catlogs
     * @param int $level
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function getOptions($default = 0, $catlogs=[], $level=0){

        if (!$catlogs) $catlogs = self::fetchWithCache();

        $level++;
        $options = $selected = '';
        foreach ($catlogs as $catlog) {
            $prefix = str_repeat('|--', $level - 1);
            $selected = $default == $catlog->catid ? ' selected="selected"' : '';
            $options.= '<option value="'.$catlog->catid.'"'.$selected.'>'.$prefix.$catlog->name.'</option>';
            if ($catlog->childs) {
                $options.= self::getOptions($default, $catlog->childs, $level);
            }
        }
        return $options;
    }

    /**
     * @param $catid
     * @return array
     */
    public static function fetchAllChildIds($catid){
        static $catloglist;
        if (!$catloglist) {
            $catloglist = self::all();
        }

        $Ids = [$catid];
        foreach ($catloglist as $catlog) {
            if ($catlog->fid == $catid){
                $Ids[] = $catlog->catid;
                $Ids = array_merge($Ids, self::fetchAllChildIds($catlog->catid));
            }
        }
        return $Ids;
    }

    /**
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function updateCache()
    {
        $catlogs = [];
        self::with('childs')->available()->orderBy('displayorder')->get()->map(function ($catlog) use (&$catlogs){
            $catlogs[$catlog->fid][] = $catlog;
        });
        $data = $catlogs ? $catlogs[0] : [];
        Cache::forever('postCatlogs', $data);
    }

    /**
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function fetchWithCache(){
        $data = Cache::get('postCatlogs');
        if (!is_array($data)) {
            self::updateCache();
            return self::fetchWithCache();
        }
        return $data;
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeEnable($query)
    {
        return $query->where('enable', 1);
    }

    /**
     * @param $query
     * @return mixed
     */
    public function scopeAvailable($query)
    {
        return $query->where('available', 1);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function posts()
    {
        return $this->hasMany(PostItem::class, 'catid', 'catid');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function childs()
    {
        return $this->hasMany(PostCatlog::class, 'fid', 'catid');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(PostCatlog::class, 'fid', 'catid');
    }
}
